import { useState, useRef, useCallback, FC } from 'react'
import { Button, Space, message, Popconfirm, Form, Flex } from 'antd'
import { HsAdminTablePage, HsAdminInput, HsAdminForm, HsAdminSpin } from '@hs-admin/base-components'
import { EMPTYTEXT, usePage } from '@hs-admin/utils'
import { projectStageType } from '@/utils/type'
import DetailModal from './detail'
import { deleteProjectList, getProjectList } from '@/api/developCenter/project'
import { handleButtonShow } from '@/utils/tools'
import { HsAdminEditProject } from '@hs-admin/components'
import { getProjectSourceType } from '@hs-admin/api'

const Project: FC = () => {
  const { pagination, resetPage }: { pagination: UsePageProps; resetPage: () => void } = usePage(callList)
  // 搜索
  const handleSearch = useCallback(() => {
    resetPage()
  }, [resetPage])
  const [form] = Form.useForm()
  const formItemOptions = [
    {
      name: 'search',
      slot: 'search',
      FormItemColProps: {
        span: 12
      }
    },
    {
      label: '项目阶段',
      name: 'stage',
      component: 'Select',
      componentProps: {
        options: [{ label: '全部', value: '' }, ...projectStageType()],
        onChange: handleSearch
      },
      FormItemColProps: {
        span: 8
      }
    }
  ]
  const [data, setData] = useState<any[]>([])
  const editRef = useRef<any>(null)
  const detailRef = useRef<any>(null)
  const [loading, setloading] = useState(true)

  const columns = [
    {
      title: '项目名称',
      dataIndex: 'name',
      ellipsis: true,
      render: (text: string, record: any) => (
        <Button
          type="link"
          onClick={() => {
            detailRef.current.showModal(record)
          }}>
          <p className="w-48 single-text-overflow text-left">{text}</p>
        </Button>
      )
    },
    {
      title: '项目类型',
      dataIndex: 'kind',
      render: (text: string) => <span>{text ? getProjectSourceType(text) : EMPTYTEXT}</span>
    },
    {
      title: '阶段',
      dataIndex: 'stage',
      render: (text: string) => <span>{text ? projectStageType(text) : EMPTYTEXT}</span>
    },
    {
      title: '阶段变化时间',
      dataIndex: 'stage_change_time',
      type: 'datetime'
    },
    {
      title: '金额',
      dataIndex: 'expected_amount',
      render: (text: number) => <span>{text ? `${Number(text / 10000).toFixed(2)}万` : EMPTYTEXT}</span>
    },
    {
      title: '项目负责人',
      dataIndex: 'owner_user.name'
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      fixed: 'right',
      render: (_: any, record: any) => (
        <Space size="small">
          {handleButtonShow('project.project.update', [record.creator_user_id, record.owner_user_id, ...record.member_user_ids]) && (
            <Button type="link" size="small" onClick={() => edit(record)}>
              编辑
            </Button>
          )}
          {handleButtonShow('project.project.delete', [record.creator_user_id, record.owner_user_id, ...record.member_user_ids]) && (
            <Popconfirm
              title="警告"
              description="确定删除该项吗?"
              onConfirm={async () => {
                await deleteProjectList({ id: record.id })
                message.success('删除成功')
                callList()
              }}>
              <Button type="link">删除</Button>
            </Popconfirm>
          )}
        </Space>
      )
    }
  ]

  // 列表查询事件
  async function callList() {
    setloading(true)
    const fieldsValues = form.getFieldsValue()
    const params = {
      page: pagination.current,
      page_size: pagination.pageSize,
      ...fieldsValues
    }
    const res = await getProjectList(params)
    const tableData = res.items
    setData(tableData)
    setloading(false)
    return res
  }
  const addProject = () => {
    editRef.current.showModal()
  }
  const edit = (record: any) => {
    editRef.current.showModal(record)
  }

  return (
    <>
      {loading && <HsAdminSpin />}
      <HsAdminForm form={form} formItemOptions={formItemOptions}>
        <div slot="search">
          <Flex align="center" gap={'middle'}>
            <Form.Item name="search" noStyle>
              <HsAdminInput placeholder="请输入项目、负责人名称" />
            </Form.Item>
            <Button type="primary" onClick={handleSearch}>
              搜 索
            </Button>
          </Flex>
        </div>
      </HsAdminForm>
      <Flex justify="justify-end">
        <Button type="primary" onClick={addProject}>
          创建项目
        </Button>
      </Flex>
      <br />
      <HsAdminTablePage columns={columns} rowKey="id" dataSource={data} pagination={pagination} size="small"></HsAdminTablePage>
      <HsAdminEditProject ref={editRef} finish={callList} />
      <DetailModal ref={detailRef} callEdit={edit} />
    </>
  )
}

export default Project
